package com.example.ssm.service;

import com.example.ssm.dao.BookRepository;
import com.example.ssm.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {
    @Autowired
    BookRepository bookRepository;
    //新增
    public void addBook(Book book){
        bookRepository.save(book);
    }
    //更新
    public String editBook(Book book){
        String result;
        if (bookRepository.existsById(book.getId())){
            bookRepository.save(book);
            result = "ok";
        }
        else result = "Update failed";
        return result;
    }
    //删除
    public String deleteById(Long id){
        String result;
        if (bookRepository.existsById(id)){
            bookRepository.deleteById(id);
            result="ok";

        }else result="not found";
        return result;
    }
    //根据id查询
    public Book findById(Long id){
        return bookRepository.findById(id).orElse(null);
    }
    //查询所有
    public List<Book> findAll(){
        return bookRepository.findAll();
    }
    //复杂查询 根据最小id查询
    public Book getMinIdBook(){
        return bookRepository.getMinIdBook();
    }

    //分页+降序
    public List<Book> getBookPage(int pageNo,int size){
        Sort.TypedSort<Book> book = Sort.sort(Book.class);
        Sort sort = book.by(Book::getPrice).descending();
        Pageable pageable = PageRequest.of(pageNo,size,sort);
        Page<Book> books = bookRepository.findAll(pageable);
        return books.getContent();
    }




}
